package cn.iocoder.ny.module.mall.controller.admin.sms;

import cn.iocoder.ny.module.mall.controller.admin.sms.vo.MallSmsVo;
import cn.iocoder.ny.module.mall.domain.SendCtyunSmsRequest;
import cn.iocoder.ny.module.mall.domain.SmsReport;
import cn.iocoder.ny.module.mall.domain.SmsReportRequest;
import cn.iocoder.ny.module.mall.service.IMallSmsService;
import cn.iocoder.ny.module.mall.utils.GetSmsUtils;
import cn.iocoder.ny.module.mall.utils.SmsErrorCodeUtil;
import cn.iocoder.ny.module.mall.utils.TySmsGetRequestIdUtils;
import cn.iocoder.ny.module.mall.utils.TySmsUtils;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mzt.logapi.service.IFunctionService;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.ny.module.mall.enums.SmsEnum.SAAS;

/**
 * @author luchunhong
 * @date 2024/10/22/ 10:51
 * @description:
 */

@RestController
@RequestMapping("mallSms")
public class MallSmsController {

    @Autowired
    private IMallSmsService mallSmsService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /*
    发送短信验证码
     */
    @PostMapping("/sendMessageCode")
    @PermitAll
    public CommonResult<String> sendMessageCode(@RequestBody @Validated MallSmsVo mallSmsVo) {
        try {
            mallSmsService.sendMessageCode(mallSmsVo);
        } catch (Exception e) {
            CommonResult.error(500, e.getMessage());
        }
        return CommonResult.success("短信发送成功");
    }

    @PostMapping("/sendMessageCodeByTyySms")
    @PermitAll
    public CommonResult sendMessageCodeByTyyy(@RequestBody SendCtyunSmsRequest sendCtyunSmsRequest) {
        if (!ObjectUtils.isEmpty(sendCtyunSmsRequest.getPhoneNumber())){
            redisTemplate.delete(SAAS+sendCtyunSmsRequest.getPhoneNumber());
            String numbers = TySmsUtils.sendSms(sendCtyunSmsRequest);
            redisTemplate.opsForValue().set(SAAS+sendCtyunSmsRequest.getPhoneNumber(),numbers,5, TimeUnit.MINUTES);
            return CommonResult.success("已发送");
        }
        return CommonResult.error(500,"手机号为空");
    }

    @PostMapping("/messageReturn")
    @PermitAll
    public void receiveSmsReport(@RequestBody SmsReportRequest smsReport) {
        List<String> smsReports = smsReport.getData();
        ObjectMapper objectMapper = new ObjectMapper();
        for (String report : smsReports) {
            try {
                SmsReport smsReport1 = objectMapper.readValue(report, SmsReport.class);
                    mallSmsService.sendMessageCodeByTyy(smsReport1);
            } catch (JsonProcessingException e) {
                System.out.println("解析失败: " + e.getMessage());
            }
        }
    }

    @GetMapping("/messageReturn")
    @PermitAll
    public CommonResult<String> getMesaage(String mobile) {
        try {
            Boolean messageCodeByTyy = mallSmsService.getMessageCodeByTyy(mobile);
            if (messageCodeByTyy){
                return CommonResult.success("短信获取成功,请注意查收");
            }
            return CommonResult.success("null");
        } catch (Exception e) {
           return CommonResult.success(e.getMessage());
        }
    }

    @PostMapping("/sendMessageByTyySmsToSaas")
    @PermitAll
    public CommonResult sendMessageByTyySms(@RequestBody SendCtyunSmsRequest sendCtyunSmsRequest) {
        if (!ObjectUtils.isEmpty(sendCtyunSmsRequest.getPhoneNumber())){
            redisTemplate.delete(SAAS+sendCtyunSmsRequest.getPhoneNumber());
            Map<String, String> stringStringMap = TySmsGetRequestIdUtils.sendSms(sendCtyunSmsRequest);
            Map<String, String> requestMap = new HashMap<>();
            requestMap.put("phoneNumber",stringStringMap.get("phoneNumber"));
            requestMap.put("requestId",stringStringMap.get("requestId"));
            System.err.println("requestIdSAMKLAFASKFAS:"+stringStringMap.get("requestId"));
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = currentDate.format(formatter);
            requestMap.put("sendTime", formattedDate);
            redisTemplate.opsForValue().set(SAAS+sendCtyunSmsRequest.getPhoneNumber(),stringStringMap.get("sessionId"),5, TimeUnit.MINUTES);
            return CommonResult.success(requestMap);
        }
        return CommonResult.error(500,"手机号为空");
    }

    @PostMapping("/messageReturnToSaas")
    @PermitAll
    public CommonResult handleSmsResponse(@RequestBody SendCtyunSmsRequest sendCtyunSmsRequest) {
        if (ObjectUtils.isEmpty(sendCtyunSmsRequest.getPhoneNumber())){
            return CommonResult.success("参数未传递");

        }
        String sms = GetSmsUtils.getSms(sendCtyunSmsRequest);
        if (!ObjectUtils.isEmpty(sms)) {
            if (isNumeric(sms)) {
                String message = SmsErrorCodeUtil.getErrorMessage(Integer.parseInt(sms));
                if (!ObjectUtils.isEmpty(message)) {
                    return CommonResult.success(message);
                }
            } else {
                return CommonResult.success("发送成功");

            }
        }
        return CommonResult.success("暂未收到");
    }
    private boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
}
